package com.crazymaker.springcloud.back.end.controller;

import com.alibaba.fastjson.JSONObject;
import com.crazymaker.springcloud.back.end.api.dto.LoginInfoDTO;
import com.crazymaker.springcloud.back.end.service.impl.SysUserAuthService;
import com.crazymaker.springcloud.common.constants.SessionConstants;
import com.crazymaker.springcloud.common.dto.UserDTO;
import com.crazymaker.springcloud.common.page.PageOut;
import com.crazymaker.springcloud.common.page.PageReq;
import com.crazymaker.springcloud.common.result.RestOut;
import com.crazymaker.springcloud.seckill.api.dto.SeckillOrderDTO;
import com.crazymaker.springcloud.seckill.remote.client.SeckillOrderClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;


@Api(value = "用户信息、基础学习DEMO", tags = {"用户信息、基础学习DEMO"})
@RestController
@RequestMapping("/api/user" )
public class UserController
{

    @Resource
    SysUserAuthService userAuthService;
    @Resource
    SeckillOrderClient seckillClient;


    @GetMapping("/{id}/detail/v1" )
    @ApiOperation(value = "获取用户信息" )
    public RestOut<JSONObject> getUser(@PathVariable("id" ) Long userId)
    {
        JSONObject data = new JSONObject();
        UserDTO dto = userAuthService.getUser(userId);
        if (null == dto)
        {
            return RestOut.error("没有找到数据" );
        }
        data.put("user", dto);
        PageReq pageReq = new PageReq();
        pageReq.setCurPage(1);
        pageReq.setPageSize(100);
        RestOut<PageOut<SeckillOrderDTO>> ordersResult = seckillClient.userOrders(userId, pageReq);
        if (null != ordersResult)
        {
            data.put("orders", ordersResult.getResult());
        }

        data.put("others", "...." );
        return RestOut.success(data).setRespMsg("操作成功" );
    }


    @PostMapping("/login/v1" )
    @ApiOperation(value = "登陆" )
    // public RestOut<String> login(@RequestParam("username") String username,
    // HttpServletResponse response) {
    public RestOut<String> login(@RequestBody LoginInfoDTO loginInfoDTO, HttpServletResponse response)
    {

        String token = userAuthService.login(loginInfoDTO);
        response.setHeader("Content-Type", "text/html;charset=utf-8" );
        response.setHeader(SessionConstants.AUTHORIZATION_HEAD, token);
        return RestOut.success(token);
    }


    /**
     * 本地调用，增加用户
     *
     * @param dto 用户dto
     * @return 响应结果
     */
    @PostMapping("/add/v1" )
    @ApiOperation(value = "增加用户" )
    public RestOut<UserDTO> addUser(@RequestBody UserDTO dto)
    {

        UserDTO dest = userAuthService.addUser(dto);
        return RestOut.success(dest).setRespMsg("操作成功" );
    }

}
